package http

import (
	"log"
	"myfirstweb/com/zgm/index"
	"myfirstweb/com/zgm/login"
	"net/http"
	"os"
)

const (
	PUBLIC = "./http/public"
)

func isExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	return os.IsExist(err)
}
func staticDirHandler(mux *http.ServeMux, prefix string) {
	mux.HandleFunc(prefix, func(w http.ResponseWriter, r *http.Request) {
		file := PUBLIC + r.URL.Path[len(prefix)-1:]
		if exists := isExists(file); !exists {
			log.Println("load fail : ", file)
		}
		http.ServeFile(w, r, file)
	})
}
func Start() {
	log.Println("start")
	mux := http.NewServeMux()
	staticDirHandler(mux, "/myfirstweb/")
	mux.HandleFunc("/login", login.LoginHandler)
	mux.HandleFunc("/loginconfirm", login.LoginConfirmHandler)
	mux.HandleFunc("/index", index.IndexHandler)
	err := http.ListenAndServe(":8080", mux)
	if err != nil {
		log.Fatal("ListenAndServe: ", err.Error())
	}
}
